﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace ERPWinFormWork
{
    public static class ApolloConfigManager
    {
        private static readonly HttpClient client = new HttpClient();
        private static readonly string apolloServerUrl = "http://47.93.123.119:8080";  // Apollo 服务器地址
        private static readonly string appId = "ERP001";  // Apollo 应用 ID
        private static readonly string cluster = "default";  // Apollo 集群名称
        private static readonly string namespaceName = "application";  // 配置命名空间（通常是 "application"）


        public static async Task<string> GetConfigAsync(string key)
        {
            // 拼接 Apollo API 的 URL
            string url = $"{apolloServerUrl}/configs/{appId}/{cluster}/{namespaceName}";

            try
            {
                // 发送 GET 请求
                HttpResponseMessage response = await client.GetAsync(url).ConfigureAwait(false);

                if (response.IsSuccessStatusCode)
                {
                    // 解析响应内容
                    string content = await response.Content.ReadAsStringAsync();

                    // 解析 JSON 数据，获取配置
                    var config = JsonConvert.DeserializeObject<dynamic>(content);
                    var value = config?.configurations?[key]?.ToString();

                    return value;
                }
                else
                {
                    throw new Exception("Error fetching config from Apollo");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
                return null;
            }
        }
    }
}